<template>
  <div class="container">
    <MyHeader 
      :date="res"
    />
    <List 
      :todo_list="todos"
    />
    <MyFooter
      :todos="todos"
      :AllCheck1="AllCheck1"
      :checkedTodo="checkedTodo"
      :detleteAll="detleteAll"
     />
  </div>
</template>

<script>

import MyHeader from './components/MyHeader.vue';
import MyFooter from './components/MyFooter.vue';
import List from './components/List.vue';

export default {
  name: 'App',
  components: {
    MyHeader,
    MyFooter,
    List,
  },
  data() {
    return {
      todos: JSON.parse(localStorage.getItem('todos')) || []
    }
  },
  methods: {
    // 增加
    res(date){
      this.todos.unshift(date)
    },
    // 勾选
    checkedTodo(id){
      this.todos.forEach(item => {
        if(item.id == id) item.done = !item.done
      });
    },
    // 删除
    deleteTodo(id){
      this.todos = this.todos.filter(todo=> todo.id !== id )
    },
    // 全选按钮
    AllCheck1(all){
      if(all !== this.todos.length) {
        this.todos.forEach(item=>{
          item.done = true
        })
      } else {
        this.todos.forEach(item => {
          item.done = false
        })
      }
    },
    // 删除已选中任务
    detleteAll(id){
      this.todos = this.todos.filter(todo => todo.id !== id)
    }
  },
  watch: {
    todos:{
      handler(value){
        localStorage.setItem('todos', JSON.stringify(value))
      },
      deep:true
    }
  },
  mounted() {
    // 绑定全局事件总线
    this.$bus.$on('deleteTodo',this.deleteTodo)
    this.$bus.$on('checkedTodo', this.checkedTodo)
    this.$bus.$on('UpDateTodo',(id,name)=>{
      this.todos.forEach(item=>{
        if(item.id == id) {
          item.title = name
        }
      })
    })
  },
  // 销毁全局事件总线
  beforeDestroy() {
    this.$bus.$off(['deleteTodo','checkedTodo','UpDateTodo'])
  },
}
</script>

<style>
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.container {
  width: 800px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
}
li {
  list-style: none;
}
</style>
